<?php


namespace app\api\controller\v9;


use app\api\controller\v2\Auth;
use app\common\lib\AliOss;
use OSS\Core\OssException;

class Upload extends Auth
{
    protected $pathType = [
        0 => 'uploads/old_version', // 旧接口
        1 => 'uploads/avatar', // 头像
        2 => 'uploads/audio', // 问答音频
        3 => 'uploads/check/left', // 认证 身份证正面
        4 => 'uploads/check/right', // 认证 身份证
        5 => 'uploads/check/cert', // 资格证书
        6 => 'uploads/call_chat/audio', // AI语音会话音频
        7 => 'uploads/ai_chat_room/avatar', // 陪聊头像
    ];

    /**
     * 文件上传大小
     * @var int
     */
    protected $file_max_size = 2097152; // 1024*1024*2=2097152  2M

    /**
     * 图片上传
     * @return \think\response\Json
     */
    public function upload()
    {
        $type = input('type/d', 0);

        $path = $this->pathType[$type] ?? '';

        if (!$path)
        {
            return show(config('code.error'), '上传类型异常');
        }

        $file = request()->file('file');

        if (isset($file))
        {
            $config = ['size' => $this->file_max_size];
            // tp5 文件上传验证
            $info = $file->validate($config)->oss($path);
            if (!$info)
            {
                return show(10034, $file->getError());
            }
            // 获取文件名
            $filename = $info->get_filename();
            // 字符串方式上传图片
            $content = file_get_contents($info->get_tmpname());

            try
            {
                $aliOss = AliOss::getInstance();
                $aliOss->ossUpload($filename, $content);
                $authPath = $filename;
                if (in_array($type, [3, 4, 5, 6]))
                {   // 设置文件私有化
                    $aliOss->setFileAuthPri($filename);

                    $authPath = $aliOss->getAuth($filename);
                    $authPath = str_replace('http://zhunle.oss-cn-beijing.aliyuncs.com', 'https://oss.goddessxzns.com', $authPath);
                }
            }
            catch (OssException $e)
            {
                return show(10034, $e->getMessage());
            }
        } else
        {
            return show(10033, 'File is not exited.');
        }

        return show(config('code.success'), '上传成功', ['path' => $filename, 'play_path' => $authPath]);
    }
}
